package com.pjq.java.ai.langchain4j.tools;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pjq.java.ai.langchain4j.entity.Appointment;
import com.pjq.java.ai.langchain4j.service.AppointmentService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 健身房教练预约工具类
 */
@Component
public class CoachAppointmentTools {

    @Autowired
    private AppointmentService appointmentService;

    @Tool(name = "获取当前日期", value = "返回今天的日期，格式为 yyyy-MM-dd")
    public String getCurrentDate() {
        return LocalDate.now().format(DateTimeFormatter.ISO_DATE);
    }

    @Tool(name = "预约教练课程", value = "根据参数，先执行 queryCoachSchedule 方法查询是否可预约，并直接告知用户是否可约，确认后再预约。")
    public String bookCoachAppointment(Appointment appointment) {
        Appointment appointmentDB = appointmentService.getOne(appointment);
        if (appointmentDB == null) {
            appointment.setId(null); // 防止大模型误设 ID
            if (appointmentService.save(appointment)) {
                return "教练课程预约成功，以下是预约详情：\n" + appointment.toString();
            } else {
                return "预约失败，请稍后重试。";
            }
        }
        return "您在相同的时间段已预约了课程，请勿重复预约。";
    }

    @Tool(name = "取消教练课程预约", value = "根据参数，查询预约是否存在，若存在则取消预约，否则返回失败信息。")
    public String cancelCoachAppointment(Appointment appointment) {
        Appointment appointmentDB = appointmentService.getOne(appointment);
        if (appointmentDB != null) {
            if (appointmentService.removeById(appointmentDB.getId())) {
                return "成功取消教练课程预约。";
            } else {
                return "取消失败，请稍后再试。";
            }
        }
        return "未查询到您的预约记录，请确认日期和时间是否正确。";
    }

    @Tool(name = "查询教练排班是否可预约", value = "根据教练名称、日期和时间段，查询该时段是否可预约。")
    public boolean queryCoachSchedule(
            @P(value = "课程名") String courseName,
            @P(value = "日期") String date,
            @P(value = "时间段，可选值：上午、下午、晚上") String time,
            @P(value = "教练名字", required = false) String coachName
    ) {
        System.out.println("正在查询教练排班是否可预约...");
        System.out.println("课程：" + courseName);
        System.out.println("日期：" + date);
        System.out.println("时间段：" + time);
        System.out.println("教练姓名：" + coachName);
        // TODO: 实现教练排班查询逻辑
        // 1. 若未指定课程类型，则根据教练名 + 日期 + 时间段 查询是否有排班
        // 2. 若有排班，则检查该时间段是否已满
        // 3. 若未满则返回 true，否则 false
        return true; // 目前先返回 true，实际应根据数据库排班信息判断
    }


}
